package com.coolwen.service;

import com.alibaba.fastjson.JSON;
import com.coolwen.dao.RoleMapper;
import com.coolwen.dao.RoleResourceMapper;
import com.coolwen.dao.UserMapper;
import com.coolwen.dao.UserRoleMapper;
import com.coolwen.entity.*;
import com.coolwen.util.EndecryptUtils;
import com.coolwen.util.PagedResult;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.xml.crypto.Data;
import java.util.*;

/**
 * 功能概要：UserService实现类
 * Created by user on 2016/6/4.
 */

@Service("userService")
public class UserServiceImpl implements UserService {


    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private UserMapper userDao;


    @Autowired
    private UserRoleMapper userRoleDao;

    @Override
    public int delete(Integer id) {
        return 0;
    }

    @Override
    public int add(User user) {

        User u = loadByUserName(user.getUsername());
        if (u != null)
            throw new ShopException("要添加的用户名已经存在");

        u = EndecryptUtils.md5Password(user);
        userDao.insertSelective(u);
        int id = u.getId();
        return id;
    }

    @Override
    public User add(User user, List<Integer> rids) {
        Integer id = this.add(user);
        logger.info("add配置id:" + JSON.toJSON(id));
        if (rids != null) {
            for (Integer rid : rids) {
                UserRole userRole = new UserRole();
                userRole.setUserId(id);
                userRole.setRoleId(rid);
                logger.info("add配置rid:" + JSON.toJSON(rid));
                userRoleDao.insertSelective(userRole);
            }
        }
        //       User u = userDao.selectByPrimaryKey(user.getId());

        return user;
    }

    @Override
    public User load(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public User loadByUserName(String userName) {
        return userDao.selectUserByUserName(userName);
    }

    @Override
    public int update(User record) {
        logger.info("update配置rids:" + JSON.toJSON(record));
        //       userDao.updateByPrimaryKeySelective(record);
        User u = EndecryptUtils.md5Password(record);
        u.setId(record.getId());
        logger.info("update加密配置rids:" + JSON.toJSON(u));
        return userDao.updateByPrimaryKeySelective(u);
    }

    @Override
    public int updateUserLtime(User record) {
        Integer id = record.getId();
        return userDao.updateUserLtime(id, new Date());

    }

    @Override
    public int update(User record, List<Integer> rids) {
        userRoleDao.deleteByUid(record.getId());

        if (rids != null) {
            for (int rid : rids) {
                UserRole ur = new UserRole();
                ur.setUserId(record.getId());
                ur.setRoleId(rid);
                userRoleDao.insertSelective(ur);
            }
        }
        this.update(record);

        return 0;
    }

    @Override
    public List<User> list() {
        return userDao.ListUser();
    }

    @Override
    public User loadUserRole(Integer uid) {
        return userDao.loadUserRole(uid);
    }

    @Override
    public List<Resource> listUserRes(Integer uid) {
        return userDao.loadUserRes(uid);
    }

    @Override
    public List<Role> listUserRoles(Integer uid) {
        User u = this.loadUserRole(uid);

        return u.getRoles();
    }

    @Override
    public List<String> listRoleByUser(Integer uid) {
        User u = this.loadUserRole(uid);
        List<String> roles = new ArrayList<String>();
        for (Role r : u.getRoles()) {
            roles.add(r.getRole());
        }
        return roles;
    }

    @Override
    public User login(String username, String password) {
        User u = userDao.selectUserByUserName(username);
        if (u == null) throw new UnknownAccountException("用户名或者密码错误!");
        if (!EndecryptUtils.checkMd5Password(username, password, u.getSalt(), u.getPassword()))
            throw new UnknownAccountException("用户名或者密码错误!");

        if (u.getStatus())
            throw new LockedAccountException("用户已经被锁定");
        return u;
    }

    @Override
    public Pager<User> find(String name) {
        int pageSize = SystemContext.getPageSize();
        int pageOffset = SystemContext.getPageOffset();
//        SystemContext.getOrder();
//        SystemContext.getPageIndex();
//        SystemContext.getSort();
        Pager<User> pages = new Pager<User>();
        Map<String, Object> params = new HashMap<String, Object>();
//        if (params == null) params = new HashMap<String, Object>();
        if (name != null && !name.equals(""))
            params.put("name", "%" + name + "%");
//        params.put("name",)
        params.put("pageSize", pageSize);
        params.put("pageOffset", pageOffset);

        //       logger.info("update加密配置params:" + JSON.toJSON(params));
        List<User> datas = userDao.find(params);
        int totalRecord = userDao.find_count(params);
        pages.setDatas(datas);
        pages.setPageOffset(pageOffset);
        pages.setPageSize(pageSize);
        pages.setTotalPage(totalRecord);
        return pages;
    }


    /**
     * @param userName 查询条件，可为空
     * @param pageNo   查询条件，可为空，默认取1
     * @param pageSize 查询条件，可为空，默认取10
     * @return
     * @author
     * @since 2015年10月23日
     */
//    @Override
//    public PagedResult<User> queryByPage(String userName, Integer pageNo, Integer pageSize) {
//        pageNo = pageNo == null ? 1 : pageNo;
//        pageSize = pageSize == null ? 10 : pageSize;
//        PageHelper.startPage(pageNo, pageSize);  //startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
//        return BeanUtil.toPagedResult(userDao.selectUserSByUserName(userName));
//    }
}
